<template>
  <el-card class="wrapper" v-loading="loading">
    <div class="movie-wrapper">
      <div class="row">
        <span class="label">电影名称</span>:
        <span class="value">{{ movie.title }}</span>
      </div>
      <div class="row">
        <span class="label">导演</span>:
        <span class="value">{{ movie.directors && movie.directors.map(({name}) => name).join(',') }}</span>
      </div>
      <div class="row">
        <span class="label">上映年份</span>:
        <span class="value">{{ movie.pub_year }}</span>
      </div>
      <div class="row">
        <el-button type="primary" @click="handleReviewCreate">创建影评</el-button>
      </div>
    </div>
    <div class="table-wrapper">
      <review-table :data="list" @delete="handleReviewDelete" @update="handleReviewUpdate"/>
    </div>
    <div class="pagination-wrapper">
      <el-pagination
          background
          @size-change="handleSizeChange"
          :current-page.sync="watchData.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="watchData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </div>
    <el-dialog
        :title="formTitle"
        :visible.sync="formVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <review-update
          :data="currentReview"
          @submit="handleReviewSubmit"
          @cancel="handleReviewCancel"
      />
    </el-dialog>
  </el-card>
</template>

<script>
  import ReviewTable from "./components/ReviewTable";
  import ReviewUpdate from "@/views/components/ReviewUpdate";
  import { createReview, deleteReviews, getReviewDetail, getReviewList, updateReview } from "@/services";

  export default {
    name: "ReviewListQuery",
    components: {
      ReviewTable,
      ReviewUpdate
    },
    data() {
      return {
        watchData: {
          current: 1,
          pageSize: 10
        },
        total: 0,
        list: [],
        loading: false,
        movie: {},
        formTitle: '新增影评',
        formVisible: false,
        currentReview: {},
      };
    },
    watch: {
      watchData: {
        deep: true,
        handler(v) {
          this.$router
            .replace({ query: { ...this.$route.query, ...v } })
            .catch(err => {
            });
          this.fetchReviewList();
        }
      },
      $route: {
        immediate: true,
        handler() {
          this.initialState();
        }
      }
    },
    methods: {
      handleReviewDelete({ id, title }) {
        this.$confirm(`确认删除标题为 "${title}" 的影评吗？`, "删除确认")
          .then(() => {
            this.loading = true;
            deleteReviews(id)
              .then(() => {
                this.$message.success("删除成功");
                this.fetchReviewList();
              })
              .catch(err => {
                this.$message.error(`删除失败: ${err.message}`);
              })
              .finally(() => {
                this.loading = false;
              });
          })
          .catch(() => {
          });
      },
      async handleReviewUpdate({ id }) {
        this.formTitle = "更新影评"
        try {
          this.currentReview = await getReviewDetail(id);
          this.$nextTick(() => {
            this.formVisible = true
          })
        } catch (err) {
          this.$message.error('影评详情获取失败，请重试.')
        }
      },
      handleReviewCreate() {
        this.formTitle = "创建影评"
        this.currentReview = {
          subject_id: this.movie.id
        }

        this.$nextTick(() => {
          this.formVisible = true
        })
      },
      handleReviewCancel() {
        this.formVisible = false
      },
      handleReviewSubmit(data) {
        const isUpdate = !!data.id
        const func = isUpdate ? updateReview : createReview;
        const loading = this.$loading({ fullscreen: true })
        func(data)
          .then(() => {
            const message = isUpdate ? `更新成功` : `创建成功`;
            this.$message.success(message);
            this.currentReview = {
              subject_id: this.movie.id
            }
            this.formVisible = false
            if (isUpdate) {
              this.fetchReviewList()
            } else {
              if (this.watchData.current === 1) {
                this.fetchReviewList()
              } else {
                this.watchData.current = 1
              }
            }
          })
          .catch(err => this.$message.error(err.message))
          .finally(() => (loading.close()));
      },

      handleSizeChange(size) {
        this.watchData.pageSize = size;
      },
      fetchReviewList() {
        this.loading = true;
        getReviewList(this.queryParams)
          .then(res => {
            const { reviews, subject, total } = res;
            this.total = total;
            this.list = reviews;
            this.movie = subject
          })
          .catch(err => this.$message.error(`获取影评列表失败: ${err.message}`))
          .finally(() => (this.loading = false));
      },
      initialState() {
        const {
          current,
          pageSize,
        } = this.$route.query;
        this.watchData = {
          current: +current || 1,
          pageSize: +pageSize || 10
        };
      }
    },
    computed: {
      queryParams() {
        return {
          start: (this.watchData.current - 1 || 0) * this.watchData.pageSize,
          limit: this.watchData.pageSize,
          id: this.$route.params.id
        };
      }
    },
    created() {
      this.initialState();
    }
  };
</script>

<style lang="scss" scoped>
  .wrapper {
    min-height: calc(100vh - 56px - 48px);
    padding: 20px;

    .movie-wrapper {
      .row {
        margin-bottom: 10px;

        .label {
          display: inline-block;
          width: 4em;
          text-align: justify;
          text-align-last: justify;
        }

        .value {
          font-weight: 600;
        }
      }
    }

    .table-wrapper {
      margin: 20px 0;
    }
  }
</style>